package com.pansky.crm.controller.system;

import com.pansky.crm.common.mybatisplus.ApiResult;
import com.pansky.crm.config.redis.RedisBean;
import com.pansky.crm.entity.bo.EmployeeLoginFormDTO;
import com.pansky.crm.entity.vo.EmployeeInfo;
import com.pansky.crm.entity.vo.KaptchaVO;
import com.pansky.crm.service.impl.LoginService;
import com.pansky.crm.util.TokenUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;


@RestController
@Slf4j
@RequestMapping("/session")
public class LoginController {


    @Autowired
    private RedisBean redisBean;

    @Autowired
    private LoginService loginService;
    /**
     * 注销登陆
     * @param token
     * @return
     */
    @GetMapping("/logOut")
    @ApiOperation(value = "登出", notes = "登出")
    public ApiResult<String> logout(@RequestParam String token) {
        Subject subject = SecurityUtils.getSubject();
        Claims tokenBody = TokenUtil.getTokenBody(token);
        //注销
        redisBean.del("LOGIN_TOKEN:" + tokenBody.getSubject());
        redisBean.del("LOGIN_REFRESH_TOKEN:" + tokenBody.getSubject());
        subject.logout();
        return ApiResult.ok("成功注销");
    }

    @PostMapping("/login")
    @ApiOperation(value = "登陆", notes = "登陆")
    public ApiResult<EmployeeInfo> login(@Valid @RequestBody EmployeeLoginFormDTO loginForm, HttpServletRequest request, HttpServletResponse response) {
        log.info("EmployeeLoginFormDTO is {}", loginForm.toString());
        return loginService.login(loginForm, request);

    }
    @GetMapping("/verificationCode")
    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    public ApiResult<KaptchaVO> verificationCode() {
        return loginService.verificationCode();
    }

    @GetMapping("/get")
    @ApiOperation(value = "获取session", notes = "获取session")
    public ApiResult<EmployeeInfo> getSession(@RequestHeader String token) {
        return loginService.getSession(token);
    }
}
